import sdk from '../core/index';
import { configKey } from "../config";
import { config } from "../config";
import { Icard2 } from "../core/tool/Icard2";
import common from "../core/tool/common";
import { asyncStaticToInstance, staticToInstance } from './base/LegacyServiceAdapter';
import { ModernTalentService } from './ModernTalentService';

/**
 * 血统服务类 - 使用适配器模式支持现代化迁移
 * 职责：
 * 1. 血统管理
 * 2. 血统经验处理
 * 3. 血统能力计算
 * 4. 血统展示
 * 5. 向现代化服务的适配
 */
export class TalentService {

    /**
     * 添加血统
     * @param currentTalents 当前血统列表
     * @param talentId 血统ID
     * @returns 添加结果
     */
    static addTalent(currentTalents: any[], talentId: string, count: number): {
        success: boolean;
        message: string;
        newTalentList: any[];
        levelChanged: boolean;
    } {
        const talentConfig = config.get(configKey.配置_血统)?.get(talentId);
        if (!talentConfig) {
            return {
                success: false,
                message: '血统不存在',
                newTalentList: currentTalents,
                levelChanged: false
            };
        }

        let newTalentList = [...currentTalents];
        let levelChanged = false;
        let totalExpGained = 0;
        let qualityUpgrades = 0;
        let newTalentCount = 0;

        // 执行count次血统添加
        for (let i = 0; i < count; i++) {
            // 检查是否已经拥有此血统
            const existingTalent = newTalentList.find(item => item.id === talentId);
            
            if (existingTalent) {
                // 提升血统品质
                const quality_max = 10 + existingTalent.quality * 10;
                const _quality = sdk.tool.common.randomWeight({ min: 0, max: quality_max });
                const addExp = sdk.tool.common.random(1, 100);
                
                if (_quality == quality_max) {
                    existingTalent.quality += 1;
                    qualityUpgrades++;
                    levelChanged = true;
                } else {
                    existingTalent.exp_now += addExp;
                    totalExpGained += addExp;
                }
            } else {
                // 新增血统
                const newTalent = {
                    id: talentId,
                    level: 1,
                    exp_now: 0,
                    exp_max: 100,
                    quality: 1 // quality.F
                };
                
                newTalentList.push(newTalent);
                newTalentCount++;
                levelChanged = true;
            }
        }

        // 构建返回消息
        let message = '';
        if (newTalentCount > 0) {
            message += `已获得${newTalentCount}个${talentConfig.name}血统`;
        }
        if (qualityUpgrades > 0) {
            if (message) message += '，';
            message += `品质提升${qualityUpgrades}次`;
        }
        if (totalExpGained > 0) {
            if (message) message += '，';
            message += `获得${totalExpGained}点血统经验`;
        }

        return {
            success: true,
            message: message || `使用了${count}个${talentConfig.name}血统道具`,
            newTalentList,
            levelChanged
        };
    }

    /**
     * 获取品质名称
     * @param quality 品质值
     * @returns 品质名称
     */
    private static getQualityName(quality: number): string {
        const qualityNames = ['F', 'E', 'D', 'C', 'B', 'A', 'S', 'SS', 'SSR'];
        return qualityNames[quality] || 'F';
    }

    /**
     * 获取血统配置
     * @param id 血统ID
     * @returns 血统配置
     */
    private static getTalentConfig(id: string): any {
        const cfg = config.get(configKey.配置_血统)?.get(id);
        if (!cfg) {
            throw new Error(`血统配置不存在: ${id}`);
        }
        return cfg;
    }

    /**
     * 获取血统最大等级
     * @param id 血统ID
     * @returns 最大等级
     */
    private static getMaxLevel(id: string): number {
        const cfg = this.getTalentConfig(id);
        return cfg.table.split('\n').length;
    }

    /**
     * 添加经验
     * @param currentTalents 当前血统列表
     * @param exp 经验值
     * @returns 添加结果
     */
    @staticToInstance(ModernTalentService)
    static addExperience(currentTalents: any[], exp: number): {
        success: boolean;
        message: string;
        newTalentList: any[];
        levelUpMessages: string[];
    } {
        if (currentTalents.length === 0) {
            return {
                success: false,
                message: '没有血统可以获得经验',
                newTalentList: currentTalents,
                levelUpMessages: []
            };
        }

        const expPerTalent = exp / currentTalents.length;
        const levelUpMessages: string[] = [];
        const newTalentList = currentTalents.map(item => {
            const newItem = { ...item };
            newItem.exp_now += expPerTalent;
            
            if (newItem.exp_now >= newItem.exp_max) {
                const maxLevel = this.getMaxLevel(newItem.id);
                if (newItem.level < maxLevel) {
                    const cfg = this.getTalentConfig(newItem.id);
                    newItem.level++;
                    newItem.exp_now = 0;
                    newItem.exp_max = 100 * newItem.level;
                    levelUpMessages.push(`${cfg.name}血统已提升至${newItem.level}级!`);
                } else {
                    newItem.exp_now = newItem.exp_max;
                }
            }
            
            return newItem;
        });

        return {
            success: true,
            message: `获得经验: ${exp}`,
            newTalentList,
            levelUpMessages
        };
    }





    /**
     * 获取血统详情
     * @param talentId 血统ID
     * @returns 血统详情
     */
    static getTalentDetails(talentId: string): {
        success: boolean;
        talent?: {
            id: string;
            name: string;
            desc: string;
            level: number;
            skills: string[];
            attributes: { [key: string]: number };
        };
    } {
        const talentConfig = config.get(configKey.配置_血统)?.get(talentId);
        if (!talentConfig) {
            return {
                success: false
            };
        }

        return {
            success: true,
            talent: {
                id: talentId,
                name: talentConfig.name,
                desc: talentConfig.desc,
                level: talentConfig.level || 1,
                skills: talentConfig.skills || [],
                attributes: talentConfig.attributes || {}
            }
        };
    }

    /**
     * 获取血统列表信息
     * @param talentIds 血统ID列表
     * @returns 血统列表
     */
    static getTalentList(talentIds: string[]): {
        id: string;
        name: string;
        desc: string;
        level: number;
    }[] {
        const talentList: {
            id: string;
            name: string;
            desc: string;
            level: number;
        }[] = [];

        talentIds.forEach(talentId => {
            const details = this.getTalentDetails(talentId);
            if (details.success && details.talent) {
                talentList.push({
                    id: details.talent.id,
                    name: details.talent.name,
                    desc: details.talent.desc,
                    level: details.talent.level
                });
            }
        });

        return talentList;
    }

    /**
     * 计算血统属性加成
     * @param talentIds 血统ID列表
     * @returns 属性加成
     */
    static calculateTalentAttributes(talentIds: string[]): { [key: string]: number } {
        const totalAttributes: { [key: string]: number } = {};

        talentIds.forEach(talentId => {
            const details = this.getTalentDetails(talentId);
            if (details.success && details.talent) {
                Object.entries(details.talent.attributes).forEach(([key, value]) => {
                    totalAttributes[key] = (totalAttributes[key] || 0) + value;
                });
            }
        });

        return totalAttributes;
    }

    /**
     * 获取血统技能
     * @param talentIds 血统ID列表
     * @returns 血统技能列表
     */
    static getTalentSkills(talentIds: string[]): string[] {
        const skills: string[] = [];

        talentIds.forEach(talentId => {
            const details = this.getTalentDetails(talentId);
            if (details.success && details.talent) {
                skills.push(...details.talent.skills);
            }
        });

        return [...new Set(skills)]; // 去重
    }

    /**
     * 创建血统展示卡片
     * @param talentId 血统ID
     * @returns 血统卡片
     */
    static createTalentCard(talentId: string): Icard2 {
        const card = sdk.tool.card.create2();
        sdk.prop.client_talent(talentId, undefined, card, true);
        return card;
    }

    /**
     * 获取血统统计信息
     * @param talentIds 血统ID列表
     * @param experience 血统经验
     * @returns 统计信息
     */
    static getTalentStats(talentIds: string[], experience: number): {
        talentCount: number;
        totalLevel: number;
        averageLevel: number;
        experience: number;
        attributeBonus: { [key: string]: number };
        skillCount: number;
    } {
        const talentList = this.getTalentList(talentIds);
        const totalLevel = talentList.reduce((sum, talent) => sum + talent.level, 0);
        const attributeBonus = this.calculateTalentAttributes(talentIds);
        const skills = this.getTalentSkills(talentIds);

        return {
            talentCount: talentList.length,
            totalLevel,
            averageLevel: talentList.length > 0 ? totalLevel / talentList.length : 0,
            experience,
            attributeBonus,
            skillCount: skills.length
        };
    }

    /**
     * 检查血统是否可用
     * @param talentId 血统ID
     * @param playerLevel 玩家等级
     * @returns 是否可用
     */
    static isTalentAvailable(talentId: string, playerLevel: number): {
        available: boolean;
        reason?: string;
    } {
        const details = this.getTalentDetails(talentId);
        if (!details.success) {
            return {
                available: false,
                reason: '血统不存在'
            };
        }

        // 这里可以添加血统解锁条件的检查
        // 例如：需要达到特定等级、拥有特定物品等
        const requiredLevel = details.talent!.level || 1;
        if (playerLevel < requiredLevel) {
            return {
                available: false,
                reason: `需要达到 ${requiredLevel} 级`
            };
        }

        return {
            available: true
        };
    }

    /**
     * 获取血统进化信息
     * @param talentId 血统ID
     * @param currentLevel 当前等级
     * @returns 进化信息
     */
    static getTalentEvolution(talentId: string, currentLevel: number): {
        canEvolve: boolean;
        nextLevel: number;
        requiredExp: number;
        evolutionEffects: {
            attributeGain: { [key: string]: number };
            newSkills: string[];
        };
    } {
        const details = this.getTalentDetails(talentId);
        if (!details.success) {
            return {
                canEvolve: false,
                nextLevel: currentLevel,
                requiredExp: 0,
                evolutionEffects: {
                    attributeGain: {},
                    newSkills: []
                }
            };
        }

        const nextLevel = currentLevel + 1;
        const requiredExp = nextLevel * 1000; // 简单的进化经验公式

        return {
            canEvolve: true,
            nextLevel,
            requiredExp,
            evolutionEffects: {
                attributeGain: {
                    '物理攻击': 10,
                    '魔法攻击': 10,
                    '生命值': 50
                },
                newSkills: [] // 可以根据血统添加新技能
            }
        };
    }

    /**
     * 处理血统进化
     * @param talentId 血统ID
     * @param currentLevel 当前等级
     * @param currentExp 当前经验
     * @param requiredExp 需要的经验
     * @returns 进化结果
     */
    static processTalentEvolution(
        talentId: string,
        currentLevel: number,
        currentExp: number,
        requiredExp: number
    ): {
        success: boolean;
        message: string;
        newLevel: number;
        newExp: number;
        effects: {
            attributeGain: { [key: string]: number };
            newSkills: string[];
        };
    } {
        if (currentExp < requiredExp) {
            return {
                success: false,
                message: '经验不足',
                newLevel: currentLevel,
                newExp: currentExp,
                effects: {
                    attributeGain: {},
                    newSkills: []
                }
            };
        }

        const evolution = this.getTalentEvolution(talentId, currentLevel);
        if (!evolution.canEvolve) {
            return {
                success: false,
                message: '无法进化',
                newLevel: currentLevel,
                newExp: currentExp,
                effects: {
                    attributeGain: {},
                    newSkills: []
                }
            };
        }

        const newLevel = currentLevel + 1;
        const newExp = currentExp - requiredExp;

        return {
            success: true,
            message: `血统进化成功！等级提升到 ${newLevel}`,
            newLevel,
            newExp,
            effects: evolution.evolutionEffects
        };
    }
} 